package com.laiketui.common.service.dubbo.index;


import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.laiketui.common.api.PublicGoodsService;
import com.laiketui.common.api.PubliceService;
import com.laiketui.common.api.index.IndexDataService;
import com.laiketui.common.api.index.IndexItemService;
import com.laiketui.common.mapper.*;
import com.laiketui.common.service.dubbo.BaseServiceImpl;
import com.laiketui.common.service.dubbo.PublicGoodsServiceImpl;
import com.laiketui.common.utils.tool.ImgUploadUtils;
import com.laiketui.common.utils.tool.cache.RedisDataTool;
import com.laiketui.core.cache.RedisUtil;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.domain.index.IndexData;
import com.laiketui.domain.index.IndexItem;
import com.laiketui.domain.lktconst.DictionaryConst;
import com.laiketui.domain.lktconst.ErrorCode;
import com.laiketui.domain.material.Material;
import com.laiketui.domain.mch.AdminModel;
import com.laiketui.domain.mch.MchModel;
import com.laiketui.domain.product.ProductListModel;
import com.laiketui.domain.productClass.ProductClass;
import com.laiketui.domain.vo.MainVo;
import com.laiketui.domain.vo.index.IndexDataVo;
import com.laiketui.domain.vo.product.ProductInfoVo;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 34496
 * @description 针对表【lk_index_data(小程序主页基本信息)】的数据库操作Service实现
 * @createDate 2025-01-07 22:43:59
 */
@Service
public class IndexDataServiceImpl implements IndexDataService {

    private final int defaultStoreId = 1;

    //一级分类
    private static final int firstClassLevel = 1;

    //显示
    private static final int isDisplay = 1;

    //新品推荐类型
    private static final Integer newProductType = 8;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IndexItemService indexItemService;

    @Autowired
    private IndexDataMapper indexDataMapper;

    @Autowired
    private IndexItemMapper indexItemMapper;

    @Autowired
    private ProductListModelMapper productListModelMapper;

    @Autowired
    private PubliceService publiceService;

    @Autowired
    private ProductClassMapper productClassMapper;

    @Autowired
    private MchModelMapper mchModelMapper;

    @Autowired
    private MaterialMapper materialMapper;


    @Override
    public void insertIndexData(IndexDataVo vo) throws LaiKeAPIException{
        AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
        Integer categoryId = vo.getCategoryId();
        if(categoryId != null){
            ProductClass productClass = productClassMapper.selectByPrimaryKey(categoryId);
            if(productClass == null){
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_,"分类ID号已失效，请重新修改。");
            }
            if(productClass != null && Objects.equals(productClass.getRecycle(), GloabConst.RecycleType.IS_RECYCLE)){
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_,"当前分类已下架，请重新修改。");
            }
        }
        IndexData data = new IndexData();
        data.setType(vo.getType());
        data.setFeedId(vo.getFeedId());
        data.setContent(vo.getContent());
        data.setBackgroundImg(vo.getBackgroundImg());
        data.setDetailImg(vo.getDetailImg());
        data.setCategoryId(vo.getCategoryId());
        data.setMainTitle(vo.getMainTitle());
        data.setSort(vo.getSort());
        data.setStatus(vo.getStatus());
        data.setSubtitle(vo.getSubtitle());
        data.setStoreId(vo.getStoreId());
        indexDataMapper.insert(data);
        String itemsJson = vo.getItems();
        List<IndexItem> items = JSONObject.parseObject(itemsJson, new TypeReference<List<IndexItem>>() {
        });
        if(Objects.isNull(items)){
            return;
        }
        items.forEach(i -> {
            IndexItem indexItem = new IndexItem();
            Integer productId = i.getProductId();
            if(productId != null){
                ProductListModel productListModel = new ProductListModel();
                productListModel.setId(productId);
                productListModel = productListModelMapper.selectOne(productListModel);
                String status = productListModel.getStatus();
                if(productListModel == null){
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_,"商品ID号已失效，请重新修改。");
                }
                if(productListModel != null && Objects.equals(status,DictionaryConst.GoodsStatus.OFFLINE_GROUNDING)){
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_,"商品ID号已下架，请重新修改。");
                }
            }
            indexItem.setIndexId(data.getId());
            indexItem.setType(i.getType());
            indexItem.setCoverPath(i.getCoverPath());
            indexItem.setProductId(i.getProductId());
            indexItem.setCategoryId(i.getCategoryId());
            indexItem.setMainTitle(i.getMainTitle());
            indexItem.setSubtitle(i.getSubtitle());
            indexItem.setMaterialId(i.getMaterialId());
            indexItem.setVideoPath(i.getVideoPath());
            indexItem.setArticlePath(i.getArticlePath());
            indexItem.setContent(i.getContent());
            indexItem.setSort(i.getSort());
            indexItem.setStoreId(vo.getStoreId());
            indexItemMapper.insert(indexItem);
        });
    }

    @Override
    public void updateIndexData(IndexDataVo vo) throws LaiKeAPIException{
            AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            Integer categoryId = vo.getCategoryId();
            if(categoryId != null){
                ProductClass productClass = productClassMapper.selectByPrimaryKey(categoryId);
                if(productClass == null){
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_,"分类ID号已失效，请重新修改。");
                }
                if(productClass != null && Objects.equals(productClass.getRecycle(), GloabConst.RecycleType.IS_RECYCLE)){
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_,"当前分类已下架，请重新修改。");
                }
            }
            IndexData data = new IndexData();
            data.setId(vo.getId());
            data = indexDataMapper.selectOne(data);
            data.setFeedId(vo.getFeedId());
            data.setBackgroundImg(vo.getBackgroundImg());
            data.setDetailImg(vo.getDetailImg());
            data.setCategoryId(vo.getCategoryId());
            data.setContent(vo.getContent());
            data.setMainTitle(vo.getMainTitle());
            data.setSort(vo.getSort());
            data.setStatus(vo.getStatus());
            data.setSubtitle(vo.getSubtitle());
            data.setStoreId(vo.getStoreId());
            indexDataMapper.updateByPrimaryKey(data);
            String itemsJson = vo.getItems();
            List<IndexItem> items = JSONObject.parseObject(itemsJson, new TypeReference<List<IndexItem>>() {
            });
            if(Objects.isNull(items)){
                return;
            }
            List<IndexItem> nonNullIdList = new ArrayList<>();
            items.forEach(i -> {
                Integer id = i.getId();
                IndexItem indexItem = new IndexItem();
                Integer productId = i.getProductId();
                if(productId != null){
                    ProductListModel productListModel = new ProductListModel();
                    productListModel.setId(productId);
                    productListModel = productListModelMapper.selectOne(productListModel);
                    String status = productListModel.getStatus();
                    if(productListModel == null){
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_,"商品ID号已失效，请重新修改。");
                    }
                    if(productListModel != null && Objects.equals(Integer.valueOf(status),DictionaryConst.GoodsStatus.OFFLINE_GROUNDING)){
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_,"商品ID号:" + productId  +"已下架，请重新修改。");
                    }
                }
                if (id == null) {
                    indexItem.setIndexId(vo.getId());
                    indexItem.setType(i.getType());
                    indexItem.setCoverPath(i.getCoverPath());
                    indexItem.setProductId(i.getProductId());
                    indexItem.setCategoryId(i.getCategoryId());
                    indexItem.setVideoPath(i.getVideoPath());
                    indexItem.setArticlePath(i.getArticlePath());
                    indexItem.setContent(i.getContent());
                    indexItem.setMainTitle(i.getMainTitle());
                    indexItem.setMaterialId(i.getMaterialId());
                    indexItem.setSubtitle(i.getSubtitle());
                    indexItem.setSort(i.getSort());
                    indexItem.setStoreId(vo.getStoreId());
                    indexItemMapper.insert(indexItem);
                    nonNullIdList.add(indexItem);
                } else {
                    indexItem.setId(id);
                    indexItem = indexItemMapper.selectOne(indexItem);
                    indexItem.setIndexId(vo.getId());
                    indexItem.setType(i.getType());
                    indexItem.setCoverPath(i.getCoverPath());
                    indexItem.setProductId(i.getProductId());
                    indexItem.setCategoryId(i.getCategoryId());
                    indexItem.setVideoPath(i.getVideoPath());
                    indexItem.setArticlePath(i.getArticlePath());
                    indexItem.setContent(i.getContent());
                    indexItem.setMainTitle(i.getMainTitle());
                    indexItem.setMaterialId(i.getMaterialId());
                    indexItem.setSubtitle(i.getSubtitle());
                    indexItem.setSort(i.getSort());
                    indexItem.setStoreId(vo.getStoreId());
                    indexItemMapper.updateByPrimaryKey(indexItem);
                    nonNullIdList.add(indexItem);
                }
            });
            //删除不存在的对象
            deleteNotExistItem(nonNullIdList, vo.getId());
    }

    @Override
    public IndexData selectInfo(IndexDataVo vo) {
        AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
        IndexData indexData = new IndexData();
        indexData.setId(vo.getId());
        indexData = indexDataMapper.selectOne(indexData);
        IndexItem indexItem = new IndexItem();
        indexItem.setIndexId(indexData.getId());
        List<IndexItem> indexItems = indexItemMapper.select(indexItem);
        indexData.setItems(indexItems);
        return indexData;
    }

    @Override
    public PageInfo<IndexData> selectList(MainVo vo) {
        AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
        IndexData indexData = new IndexData();
        indexData.setStoreId(vo.getStoreId());
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<IndexData> list = indexDataMapper.select(indexData);
        list.forEach(item -> {
            if (item.getType() == 1) {
                IndexItem indexItem = new IndexItem();
                indexItem.setIndexId(item.getId());
                List<IndexItem> indexItems = indexItemMapper.select(indexItem);
                if (indexItems.size() > 0) {
                    item.setBackgroundImg(indexItems.get(0).getCoverPath());
                }
            }
        });
        PageInfo<IndexData> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public int deleteIndexData(IndexDataVo vo) {
        AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
        IndexData data = new IndexData();
        data.setId(vo.getId());
        int i = indexDataMapper.delete(data);
        IndexItem indexItem = new IndexItem();
        indexItem.setIndexId(vo.getId());
        List<IndexItem> indexItems = indexItemMapper.select(indexItem);
        indexItems.forEach(it -> {
            IndexItem item = new IndexItem();
            item.setId(it.getId());
            indexItemMapper.delete(item);
        });
        return i;
    }

    @Override
    public int updateStatus(IndexDataVo vo) {
        AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
        IndexData indexData = new IndexData();
        indexData.setId(vo.getId());
        indexData = indexDataMapper.selectOne(indexData);
        Integer status = indexData.getStatus();
        if (DictionaryConst.StatusType.STATUS_ISLINE.equals(status)) {
            indexData.setStatus(DictionaryConst.StatusType.STATUS_OFFLINE);
        }
        if (DictionaryConst.StatusType.STATUS_OFFLINE.equals(status)) {
            indexData.setStatus(DictionaryConst.StatusType.STATUS_ISLINE);
        }
        return indexDataMapper.updateByPrimaryKeySelective(indexData);
    }

    @Override
    public List<IndexData> indexDataList(IndexDataVo vo) {
        Example example = new Example(IndexData.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status", DictionaryConst.StatusType.STATUS_ISLINE);
        criteria.andEqualTo("storeId", vo.getStoreId());
        example.setOrderByClause("sort asc");
        List<IndexData> list = indexDataMapper.selectByExample(example);
        list.forEach(i -> {
            Example e = new Example(IndexItem.class);
            Example.Criteria eCriteria = e.createCriteria();
            eCriteria.andEqualTo("indexId", i.getId());
            e.setOrderByClause("sort asc");
            List<IndexItem> items = indexItemMapper.selectByExample(e);
            items = this.offlineStatusHandle(items, i.getType());
            i.setItems(items);
        });
        return list;
    }

    @Override
    public List<ProductListModel> productList(MainVo vo,String keyword) {
        if(StringUtil.isNotBlank(keyword)){
            keyword = keyword +"%";
        }
        int storeId = vo.getStoreId();
        MchModel mchModel = new MchModel();
        mchModel.setBelongStore(storeId);
        mchModel.setRecovery(GloabConst.RecycleType.NOT_RECYCLE);
        List<MchModel> mchModelList = mchModelMapper.select(mchModel);
        List<Integer> mchIds = mchModelList.stream().map(MchModel::getId).collect(Collectors.toList());
        Example example = new Example(ProductListModel.class);
        example.createCriteria()
                .andEqualTo("recycle", GloabConst.RecycleType.NOT_RECYCLE)
                .andEqualTo("status", DictionaryConst.GoodsStatus.NEW_GROUNDING)
                .andIn("mch_id",mchIds);
        if(StringUtil.isNotBlank(keyword)) {
            example.and(example.createCriteria()
                    .andLike("id", keyword)
                    .orLike("product_title", keyword));
        }
        List<ProductListModel> productListModels = productListModelMapper.selectByExample(example);
        productListModels.forEach(p ->{
            String imgPath = p.getCover_map();
            imgPath = publiceService.getImgPath(imgPath, defaultStoreId);
            p.setImgurl(imgPath);
        });
        return productListModels;
    }

    @Override
    public List<ProductClass> classList(MainVo vo, String keyword) {
        if(StringUtil.isNotBlank(keyword)){
            keyword = keyword +"%";
        }
        int storeId = vo.getStoreId();
        Example example = new Example(ProductClass.class);
        example.createCriteria().andEqualTo("recycle", GloabConst.RecycleType.NOT_RECYCLE)
                .andEqualTo("storeId",storeId)
                .andEqualTo("level",firstClassLevel)
                .andEqualTo("isDisplay",isDisplay);
        if(StringUtil.isNotBlank(keyword)){
            example.and(example.createCriteria()
                    .andLike("cid",keyword)
                    .orLike("pname",keyword));
        }
        List<ProductClass> productClassList = productClassMapper.selectByExample(example);
        productClassList.forEach(p ->{
            String img = p.getImg();
            img = publiceService.getImgPath(img, defaultStoreId);
            p.setImg(img);
        });
        return productClassList;
    }

    private void deleteNotExistItem(List<IndexItem> items, Integer id) {
        if (id == null || items.size() < 1) {
            return;
        }
        IndexItem indexItem = new IndexItem();
        indexItem.setIndexId(id);
        List<IndexItem> indexItems = indexItemMapper.select(indexItem);
        List<IndexItem> notExistItems = new ArrayList<>();
        for (IndexItem childItem : indexItems) {
            int mark = 0;
            for (IndexItem item : items) {
                if (childItem.getId().equals(item.getId())) {
                    mark++;
                }
            }
            if (mark == 0) {
                notExistItems.add(childItem);
            }
        }
        notExistItems.forEach(item -> {
            indexItemMapper.delete(item);
        });

    }

    //处理下架分类
    private List<IndexItem> offlineStatusHandle(List<IndexItem> items,Integer type){
        for (int i = 0; i < items.size();i++) {
            IndexItem item = items.get(i);
            //类型为商品
            if (item.getProductId() != null) {
                ProductListModel productListModel = new ProductListModel();
                productListModel.setId(item.getProductId());
                productListModel.setRecycle(String.valueOf(GloabConst.RecycleType.NOT_RECYCLE));
                productListModel.setStatus(String.valueOf(DictionaryConst.GoodsStatus.NEW_GROUNDING));
                ProductListModel model = productListModelMapper.selectOne(productListModel);
                if(model == null){
                    items.remove(i);
                    i--;
                }
                if (model != null) {
                    //获取第一个sku价格
                    ProductListModel productListParam = new ProductListModel();
                    productListParam.setId(model.getId());
                    BigDecimal price = productListModelMapper.getFirstGoodsPrice(productListParam);

                    ProductInfoVo product = new ProductInfoVo();
                    if (newProductType.equals(type)) {
                        product.setProductTitle(item.getMainTitle());
                        product.setPrice(price.intValue());
                        product.setProductId(item.getProductId());
                        if (StringUtil.isNotBlank(model.getCover_map())) {
                            product.setImg(item.getCoverPath());
                        }
                    } else {
                        product.setProductTitle(model.getProduct_title());
                        product.setPrice(price.intValue());
                        product.setProductId(item.getProductId());
                        if (StringUtil.isNotBlank(model.getCover_map())) {
                            product.setImg(publiceService.getImgPath(model.getCover_map(), defaultStoreId));
                        }
                    }
                    item.setProduct(product);
                }
            }
            //类型为材质分类
            if (item.getMaterialId() != null) {
                Material material = new Material();
                material.setId(item.getMaterialId());
                material.setStatus(DictionaryConst.StatusType.STATUS_ISLINE);
                material = materialMapper.selectOne(material);
                if(material == null){
                    items.remove(i);
                }
            }
            //类型为商品分类
            if(item.getCategoryId() != null){
                ProductClass productClass = new ProductClass();
                productClass.setCid(item.getCategoryId());
                productClass.setRecycle(GloabConst.RecycleType.NOT_RECYCLE);
                productClass = productClassMapper.selectOne(productClass);
                if(productClass == null){
                    items.remove(i);
                }
            }
        }

        return items;
    }

}




